package com.guxingke.typecho4j.widget.handle.user;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.guxingke.typecho4j.Typecho4jException;
import com.guxingke.typecho4j.jfinal.model.User;
import com.guxingke.typecho4j.route.DispatcherStrategy;
import com.guxingke.typecho4j.route.Route;
import com.guxingke.typecho4j.route.Routes;
import com.guxingke.typecho4j.util.StringUtil;
import com.guxingke.typecho4j.widget.WidgetHandle;
import com.guxingke.typecho4j.widget.provider.UserBaseWidget;
import com.jfinal.core.Controller;

/**
 * 用户登录的处理组件
 * 
 * @author guxingke
 *
 */
public class LoginHandleWidget extends UserBaseWidget implements WidgetHandle {

	@Override
	public void handle(Controller controller) throws Typecho4jException {
		HttpSession session = controller.getSession();

		if (session.getAttribute("user") == null) {
			validateLogin(controller);
			String name = controller.getPara("name");
			String password = controller.getPara("password");

			User user = login(name, password);
			if (user == null) {
				throw new Typecho4jException(701);
			} else {
				updateActivated(user);
				session.setAttribute("user", user);

				Integer remember = controller
						.getParaToInt("remember");

				if (remember != null) {
					HttpServletResponse response = controller
							.getResponse();
					addCookie(response, name, password);
				}
			}
		}
	}

	private void addCookie(HttpServletResponse response, String name,
			String password) {
		Cookie cookie = new Cookie("user", name + "-" + password);
		cookie.setPath("user");
		cookie.setMaxAge(30 * 24 * 60 * 60);
		response.addCookie(cookie);
	}

	private void validateLogin(Controller controller)
			throws Typecho4jException {
		String username = controller.getPara("name");
		String password = controller.getPara("password");
		if (StringUtil.isBlank(username)
				|| StringUtil.isBlank(password)) {
			throw new Typecho4jException(700);
		}
	}

	@Override
	public void configRoute(Routes routes) {
		Route loginRoute = new Route("login", this.getClass(),
				"/admin", DispatcherStrategy.REDIRECT);
		routes.addRoute(loginRoute);

	}
}
